package cn.wenlihelp.service.impl;

import cn.wenlihelp.bean.Role;
import cn.wenlihelp.mapper.RoleMapper;
import cn.wenlihelp.service.RoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {
    @Resource
    private RoleMapper roleMapper;

    @Override
    public PageInfo<Role> findAll(int page, int limit, Role role) {
        PageHelper.startPage(page, limit);
        List<Role> roles = this.findAll(role);
        return new PageInfo<>(roles);
    }

    @Override
    public List<Role> findAll(Role role) {
        return roleMapper.findAll(role);
    }

    @Override
    public List<Role> findByAccountId(Integer id) {
        return roleMapper.findByAccountId(id);
    }

    @Override
    public Role findById(Long id) {
        return roleMapper.selectByPrimaryKey(id);
    }

    @Override
    public boolean deleteByIds(Integer[] ids) {
        try {
            roleMapper.deleteByIds(ids);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean insert(Role role) {
        try {
            return roleMapper.insertSelective(role) > 0;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean updateByPrimaryKey(Role role) {
        try {
            return roleMapper.updateByPrimaryKeySelective(role) > 0;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    @Transactional
    public void resourceMapping(Integer roleId, Integer[] resourceIds) {
        //删除原有的关联关系
        this.roleMapper.deleteByRoleResourceMapping(roleId);
        //新增新的关联关系
        System.out.println(resourceIds);
        if (resourceIds != null && resourceIds.length > 0) {
            this.roleMapper.addRoleResourceMapping(roleId, resourceIds);
        }
    }
}
